<template>
    <view class="add-form-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header :title="isEdit ? '编辑施肥管理' : '新增施肥类型'"></page-header>

        <!-- 使用地块选择器组件 -->
        <land-selector
            ref="landSelector"
            @selection-change="handleLandSelectionChange"></land-selector>

        <!-- 使用条田选择器组件 -->
        <section-selector 
            ref="sectionSelector" 
            @areaChange="handleAreaChange"
            @usersChange="handleUsersChange"></section-selector>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form">
                <uni-forms-item label="施肥时间" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="formData.dateRange"
                        :border="false"
                        :label-width="200"
                        @change="dateRangeChange">
                        <view class="uni-date-picker-container">
                            <text
                                :class="{
                                    placeholder: !formData.dateRangeText,
                                }">
                                {{ formData.dateRangeText || '请选择施肥时间' }}
                            </text>
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item
                    label="施肥类型"
                    name="fertilizerType"
                    :label-width="200"
                    required>
                    <uni-data-select
                        v-model="formData.fertilizerType"
                        :localdata="fertilizerCategoryData"
                        placeholder="请选择施肥类型"></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="肥料类型" name="fertilizerCategoryId" required>
                    <uni-data-select
                        v-model="formData.fertilizerCategoryId"
                        :localdata="fertilizerTypeData"
                        placeholder="请选择肥料类型" 
                        @change="handleFertilizerCategoryIdChange"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="肥料名称" name="fertilizerNameId" required>
                    <uni-data-select
                        v-model="formData.fertilizerNameId"
                        :localdata="currentFertilizerTypesData"
                        placeholder="请选择肥料名称"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="施肥方式" name="applicationMethodId" required>
                    <uni-data-select
                        v-model="formData.applicationMethodId"
                        :localdata="applicationMethodData"
                        placeholder="请选择施肥方式"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="施肥面积" name="area" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.area"
                        placeholder="请输入"
                        disabled>
                        <template #right>
                            <view class="input-unit">亩</view>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="用量" name="dosage" required>
                    <view class="form-two-columns">
                        <uni-easyinput
                            type="digit"
                            v-model="formData.dosage"
                            placeholder="请输入总量"
                            @change="calculateDosagePerArea">
                            <template #right>
                                <view class="input-unit">kg</view>
                            </template>
                        </uni-easyinput>
                        <uni-easyinput
                            type="digit"
                            v-model="formData.calculatedDosage"
                            placeholder="请输入亩均用量"
                            @change="calculateTotalDosage">
                            <template #right>
                                <view class="input-unit">kg/亩</view>
                            </template>
                        </uni-easyinput>
                    </view>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="personInCharge" required>
                    <uni-easyinput
                        v-model="formData.personInCharge"
                        placeholder="请输入负责人姓名"
                        disabled></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="备注" name="remark">
                    <uni-easyinput
                        v-model="formData.remark"
                        placeholder="请输入备注信息"
                        type="textarea"
                        :maxlength="200"></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>

            <image-uploader ref="imageUploader" :images="formData.images" :maxCount="9" />
        </view>
        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">点击上传</view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import LandSelector from '@/components/LandSelector/index.vue'
import SectionSelector from '@/components/SectionSelector/index.vue'
import ImageUploader from '@/components/ImageUploader/index.vue'
import { fertilizer } from '@/utils/api/index.js'
import { formatDate, getDefaultDateRange } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        LandSelector,
        SectionSelector,
        ImageUploader,
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
            userInfo: 'getUserInfo',
        }),
    },
    data() {
        const defaultDateRange = getDefaultDateRange()
        return {
            isEdit: false,
            editId: null,
            isCalculating: false, // 添加计算标志位，避免循环计算
            formData: {
                fertilizerType: '',
                fertilizerCategory: '',
                fertilizerCategoryId: '',
                fertilizerTypeName: '',
                fertilizerName: '',
                fertilizerNameId: '',
                applicationMethod: '',
                applicationMethodId: '',
                area: '',
                dosage: '',
                calculatedDosage: '0',
                dateRange: defaultDateRange.dateRange,
                dateRangeText: defaultDateRange.dateRangeText,
                personInCharge: '',
                personInId: '',
                images: [],
                plotId: '', // 地块ID
                fieldId: '', // 条田ID
                remark: '', // 备注
            },
            rules: {
                dateRange: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择施肥时间',
                        },
                    ],
                },
                fertilizerCategoryId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择肥料类型',
                        },
                    ],
                },
                fertilizerNameId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择肥料名称',
                        },
                    ],
                },
                fertilizerType: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择肥料类型',
                        },
                    ],
                },
                applicationMethodId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择施肥方式',
                        },
                    ],
                },
                area: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入施肥面积',
                        },
                        {
                            format: 'number',
                            errorMessage: '请输入有效的数字',
                        },
                    ],
                },
                dosage: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入用量',
                        },
                        {
                            format: 'number',
                            errorMessage: '请输入有效的数字',
                        },
                    ],
                },
                personInCharge: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入负责人',
                        },
                    ],
                },
            },
            selectedLands: [],
            selectedSections: [],
            fertilizerCategoryData: [], // 施肥类型数据
            currentFertilizerTypesData: [], // 当前选中施肥类型的肥料名称数据
            fertilizerTypeData: [], // 肥料类型数据
            applicationMethodData: [], // 施肥方式数据
        }
    },
    onLoad(options) {
        // 加载字典数据
        this.loadDictData()

        if (options.id) {
            this.isEdit = true
            this.editId = parseInt(options.id)
            this.loadFertilizerData(this.editId)
        } else {
            // 设置默认的负责人和负责人ID
            console.log('用户信息', this.userInfo)
            this.formData.personInId = this.userInfo.id
            this.formData.personInCharge = this.userInfo.nickname
        }
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                uni.showLoading({ title: '加载字典数据...' })

                // 加载 施肥类型 字典
                await this.getDictByType('fertilization_type')
                this.fertilizerCategoryData = this.formatDictToSelectData('fertilization_type')

                // 加载 肥料类型 字典
                await this.getDictByType('fertilizer_type')
                this.fertilizerTypeData = this.formatDictToSelectData('fertilizer_type')

                // 加载 施肥方式 字典
                await this.getDictByType('fertilization_method')
                this.applicationMethodData = this.formatDictToSelectData('fertilization_method')

                uni.hideLoading()
            } catch (error) {
                console.error('加载字典数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载字典数据失败',
                    icon: 'none',
                })
            }
        },

        // 将字典数据格式化为下拉选择框所需的格式
        formatDictToSelectData(dictType) {
            const dictList = this.getDictByType(dictType)
            return dictList.map((item) => ({
                value: item.value,
                text: item.label,
            }))
        },

        async loadFertilizerData(id) {
            try {
                uni.showLoading({ title: '加载中...' })

                // 调用API获取施肥记录详情
                const res = await fertilizer.getFertilizerDetail(id)

                if (res.code === 0 && res.data) {
                    const fertilizerData = res.data

                    // 设置日期范围
                    let startDate, endDate
                    if (fertilizerData.startDate) {
                        startDate = new Date(fertilizerData.startDate)
                        endDate = fertilizerData.endDate
                            ? new Date(fertilizerData.endDate)
                            : new Date(fertilizerData.startDate)
                    } else {
                        startDate = new Date(fertilizerData.createTime)
                        endDate = new Date(fertilizerData.createTime)
                        endDate.setDate(endDate.getDate() + 1)
                    }

                    this.formData = {
                        fertilizerType: fertilizerData.fertilizerType || '',
                        fertilizerName: fertilizerData.fertilizerName || '',
                        fertilizerCategory: fertilizerData.fertilizerCategory || '',
                        fertilizerCategoryId: fertilizerData.fertilizerCategoryId || '',
                        fertilizerTypeName: fertilizerData.fertilizerTypeName || '',
                        fertilizerNameId: fertilizerData.fertilizerNameId || '',
                        applicationMethod: fertilizerData.applicationMethod || '',
                        applicationMethodId: fertilizerData.applicationMethodId || '',
                        area: fertilizerData.area ? fertilizerData.area.toString() : '',
                        dosage: fertilizerData.dosage ? fertilizerData.dosage.toString() : '',
                        dateRange: [
                            startDate.toISOString().split('T')[0],
                            endDate.toISOString().split('T')[0],
                        ],
                        dateRangeText: `${formatDate(startDate)} 至 ${formatDate(endDate)}`,
                        personInCharge: fertilizerData.personInCharge || '',
                        personInId: fertilizerData.personInId || '',
                        images: this.formatImages(fertilizerData.images),
                        plotId: fertilizerData.plotId || '',
                        fieldId: fertilizerData.fieldId || '',
                        remark: fertilizerData.remark || '',
                    }

                    // 初始化肥料名称下拉数据
                    // this.handleFertilizerTypeChange()
                    this.handleFertilizerCategoryIdChange()

                    // 计算用量/亩
                    this.calculateDosagePerArea()

                    // 等待组件加载完成后，设置地块选择状态
                    this.$nextTick(() => {
                        // 确保组件已完全加载
                        setTimeout(() => {
                            // 设置地块选择器中选中的地块
                            if (this.$refs.landSelector && fertilizerData.plotId) {
                                this.$refs.landSelector.setSelectedLands(fertilizerData.plotId)
                                this.updateSelectedLands()

                                // 更新条田选择器的地块ID
                                if (this.$refs.sectionSelector) {
                                    this.$refs.sectionSelector.setSelectedParcels(
                                        this.selectedLands
                                    )

                                    // 设置条田选择状态
                                    if (fertilizerData.fieldId) {
                                        this.$refs.sectionSelector.setSelectedFields(
                                            fertilizerData.fieldId
                                        )
                                        this.updateSelectedSections()
                                    }
                                }
                            }
                        }, 800)
                    })
                } else {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none',
                    })
                }
                uni.hideLoading()
            } catch (error) {
                console.error('加载数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none',
                })
            }
        },

        // 格式化图片字段，将字符串转为数组
        formatImages(images) {
            if (!images) return []
            if (typeof images === 'string') {
                if (images.includes(',')) {
                    return images.split(',')
                }
                return [images]
            }
            return Array.isArray(images) ? images : []
        },

        dateRangeChange(e) {
            if (e && e.length === 2) {
                const startDate = new Date(e[0])
                const endDate = new Date(e[1])
                this.formData.dateRangeText = `${formatDate(startDate)} 至 ${formatDate(endDate)}`
            } else {
                this.formData.dateRangeText = ''
            }
        },

        async handleFertilizerTypeChange() {
            // 根据选择的施肥类型，更新肥料名称下拉选项
            if (this.formData.fertilizerType) {
                try {
                    // 根据选中的施肥类型获取对应的肥料名称字典
                    const categoryValue = this.formData.fertilizerType

                    // 从字典中获取对应的肥料类型值
                    const categoryDict = this.getDictByType('fertilization_type')
                    const selectedCategory = categoryDict.find(
                        (item) => item.value === categoryValue
                    )

                    if (selectedCategory) {
                        // 加载对应的肥料名称字典
                        await this.getDictByType(selectedCategory.value)
                        this.currentFertilizerTypesData = this.formatDictToSelectData(
                            selectedCategory.value
                        )
                    } else {
                        this.currentFertilizerTypesData = []
                    }
                } catch (error) {
                    console.error('获取肥料名称字典失败:', error)
                    this.currentFertilizerTypesData = []
                }
            } else {
                this.currentFertilizerTypesData = []
            }

            // 重置肥料名称
            if (
                this.formData.fertilizerType &&
                !this.currentFertilizerTypesData.some(
                    (item) => item.value === this.formData.fertilizerNameId
                )
            ) {
                this.formData.fertilizerNameId = ''
            }
        }, 
        async handleFertilizerCategoryIdChange() {
            // 根据选择的肥料类型，更新肥料名称下拉选项
            if (this.formData.fertilizerCategoryId) {
                try {
                    // 根据选中的施肥类型获取对应的肥料名称字典
                    const categoryValue = this.formData.fertilizerCategoryId

                    // 从字典中获取对应的肥料类型值
                    const categoryDict = this.getDictByType('fertilizer_type')
                    const selectedCategory = categoryDict.find(
                        (item) => item.value === categoryValue
                    )

                    if (selectedCategory) {
                        // 加载对应的肥料名称字典
                        await this.getDictByType(selectedCategory.value)
                        this.currentFertilizerTypesData = this.formatDictToSelectData(
                            selectedCategory.value
                        )
                    } else {
                        this.currentFertilizerTypesData = []
                    }
                } catch (error) {
                    console.error('获取肥料名称字典失败:', error)
                    this.currentFertilizerTypesData = []
                }
            } else {
                this.currentFertilizerTypesData = []
            }

            // 重置肥料名称
            if (
                this.formData.fertilizerType &&
                !this.currentFertilizerTypesData.some(
                    (item) => item.value === this.formData.fertilizerNameId
                )
            ) {
                this.formData.fertilizerNameId = ''
            }
        },

        // 计算每亩用量
        calculateDosagePerArea() {
            if (this.isCalculating) return // 如果正在计算中，直接返回

            this.isCalculating = true
            if (this.formData.dosage && this.formData.area) {
                const dosage = parseFloat(this.formData.dosage)
                const area = parseFloat(this.formData.area)
                if (!isNaN(dosage) && !isNaN(area) && area > 0) {
                    this.formData.calculatedDosage = Math.round(dosage / area).toString()
                } else {
                    this.formData.calculatedDosage = '0'
                }
            } else {
                this.formData.calculatedDosage = '0'
            }
            this.isCalculating = false
        },

        // 根据亩均用量计算总量
        calculateTotalDosage() {
            if (this.isCalculating) return // 如果正在计算中，直接返回

            this.isCalculating = true
            if (this.formData.calculatedDosage && this.formData.area) {
                const dosagePerArea = parseFloat(this.formData.calculatedDosage)
                const area = parseFloat(this.formData.area)
                if (!isNaN(dosagePerArea) && !isNaN(area) && area > 0) {
                    this.formData.dosage = Math.round(dosagePerArea * area).toString()
                } else {
                    this.formData.dosage = '0'
                }
            } else {
                this.formData.dosage = '0'
            }
            this.isCalculating = false
        },

        // 更新地块选择回调
        handleLandSelectionChange() {
            this.updateSelectedLands()
        },
        handleAreaChange(area) {
            this.formData.area = area
        },

        handleUsersChange(users) {
            this.formData.personInId = users.map((item) => item.userId).join(',')
            this.formData.personInCharge = users.map((item) => item.userName).join(',')
        },

        // 更新选中的地块数据
        updateSelectedLands() {
            if (this.$refs.landSelector) {
                this.selectedLands = this.$refs.landSelector.getSelectedLands()
                console.log('更新选中的地块:', this.selectedLands)

                // 当地块选择变化时，更新条田选择器
                if (this.$refs.sectionSelector) {
                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands)
                    // 更新选中的条田
                    this.updateSelectedSections()
                }
            }
        },

        // 更新选中的条田数据
        updateSelectedSections() {
            if (this.$refs.sectionSelector) {
                this.selectedSections = this.$refs.sectionSelector.getSelectedSections()
                console.log('更新选中的条田:', this.selectedSections)
            }
        },

        validateForm() {
            // 更新选中的地块和条田
            this.updateSelectedLands()
            this.updateSelectedSections()

            // 检查是否选择了地块
            if (!this.$refs.landSelector.validate()) {
                uni.showToast({
                    title: '请选择至少一个地块',
                    icon: 'none',
                })
                return false
            }

            // 检查是否选择了条田
            if (!this.$refs.sectionSelector.validate()) {
                uni.showToast({
                    title: '请选择至少一个条田',
                    icon: 'none',
                })
                return false
            }

            return true
        },

        submitForm() {
            console.log(this.formData)
            // 使用uni-forms的验证方法
            this.$refs.form
                .validate()
                .then((result) => {
                    console.log('验证结果')
                    console.log(result)
                    console.log(this.validateForm())
                    if (this.validateForm()) {
                        this.submitFormData()
                    }
                })
                .catch((errors) => {
                    console.log('表单错误信息：', errors)
                })
        },

        async submitFormData() {
            try {
                // 获取选中的地块和条田
                this.updateSelectedLands()
                this.updateSelectedSections()

                let plotId = this.selectedLands.map((item) => item.id)
                let fieldId = this.selectedSections.map((item) => item.id)

                let plotName = this.selectedLands.map((item) => item.name)
                let fieldName = this.selectedSections.map((item) => item.name)

                // 从imageUploader组件获取最新的图片列表
                const imageList = this.$refs.imageUploader.getImageList()

                // 构建提交的数据对象
                const submitData = {
                    id: this.isEdit ? this.editId : undefined,
                    startDate: this.formData.dateRange[0],
                    endDate: this.formData.dateRange[1],
                    plotId: plotId.join(','), // 地块ID
                    fieldId: fieldId.join(','), // 条田ID
                    plotName: plotName.join(','), // 地块名称
                    fieldName: fieldName.join(','), // 条田名称
                    area: parseFloat(this.formData.area),
                    // 施肥类型
                    fertilizerType: this.formData.fertilizerType,
                    fertilizerTypeName: this.getDictLabel('fertilization_type', this.formData.fertilizerType),
                    // 肥料类型
                    fertilizerCategory: this.getDictLabel('fertilizer_type', this.formData.fertilizerCategoryId),
                    fertilizerCategoryId: this.formData.fertilizerCategoryId,
                    // 肥料名称
                    fertilizerName: this.getDictLabel(this.formData.fertilizerType, this.formData.fertilizerNameId),
                    fertilizerNameId: this.formData.fertilizerNameId,
                    // 施肥方式
                    applicationMethod: this.getDictLabel('fertilization_method', this.formData.applicationMethodId),
                    applicationMethodId: this.formData.applicationMethodId,
                    dosage: parseFloat(this.formData.dosage),
                    personInCharge: this.formData.personInCharge,
                    personInId: this.formData.personInId, // 根据实际需求设置
                    images: imageList.join(','), // 图片URL拼接
                    remark: this.formData.remark || '',
                }

                uni.showLoading({
                    title: '提交中...',
                })

                // 调用API创建或更新施肥记录
                let res
                if (this.isEdit) {
                    res = await fertilizer.updateFertilizerRecord(submitData)
                } else {
                    res = await fertilizer.createFertilizerRecord(submitData)
                }

                uni.hideLoading()

                if (res.code === 0) {
                    uni.showToast({
                        title: this.isEdit ? '修改成功' : '添加成功',
                        icon: 'success',
                        duration: 2000,
                        success: () => {
                            setTimeout(() => {
                                // 返回上一页并刷新
                                uni.navigateBack({
                                    delta: 1,
                                })
                            }, 1500)
                        },
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '操作失败',
                        icon: 'none',
                        duration: 2000,
                    })
                }
            } catch (error) {
                uni.hideLoading()
                console.error('提交数据失败:', error)
                uni.showToast({
                    title: '提交失败，请重试',
                    icon: 'none',
                    duration: 2000,
                })
            }
        },
    },
}
</script>

<style lang="scss"></style>
